/*
 * @Description: 
 * @Author: IA ia@ker.center
 * @Date: 2025-02-25 09:43:12
 */
import { createApp, toRaw } from 'vue'
// import './style.css'
import App from './App.vue'

import { createPinia } from 'pinia'
import type {PiniaPluginContext} from 'pinia'

const getStorage = (key:string) => {
    return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {}
}

const setStorage = (key:string, value:any) => {
    localStorage.setItem(key, JSON.stringify(value))
}

// const piniaPlugin = (context:PiniaPluginContext) => {
//     console.log('main.ts piniaPlugin context: ', context);
//     const {store} = context
//     console.log('main.ts piniaPlugin context store: ', store);
//     store.$subscribe(() => {
//         console.log('change')
//     })
// }

type Options = {
    key:string
}

const __piniakey__:string = 'IA'

// 函数颗粒化
const piniaPlugin = (options:Options) => {
    return (context:PiniaPluginContext) => {
        console.log('main.ts piniaPlugin context: ', context);
        const {store} = context
        console.log('main.ts piniaPlugin context store: ', store);

        const data = getStorage(`${options.key ?? __piniakey__ }-${store.$id}`)
        console.log('main.ts piniaPlugin data: ', data)

        store.$subscribe(() => {
            console.log('main.ts piniaPlugin context store $state: ', store.$state)
            console.log('main.ts piniaPlugin context store $state toRaw: ', toRaw(store.$state))
            setStorage(`${options.key ?? __piniakey__ }-${store.$id}`, toRaw(store.$state))
        })

        return {
            ...data
        }
    }
}

const store = createPinia()

store.use(piniaPlugin({
    key: "pinia"
}))

let app = createApp(App)

app.use(store)

app.mount('#app')
